/**
 * @file 创建服务器的方法
 */
import { createServer } from "http";
import { defineRouter } from "./router.js";
import { combineMiddleware } from "./middleware.js";
import { errorMiddleware, requestLocationMiddleware, requestQueryMiddleware, responseHeaderMiddleware, requestHandlerMiddleware } from "#middleware";
const defaultOptions = {
    routes: [],
    strict: false,
    serveOptions: {}
};
/** 创建服务器应用
 * @param appOptions 可选 创建服务器配置
 * @returns AppObject 对象
 */
export function createApp(appOptions = {}) {
    const { routes = [], strict = false, serveOptions = {}, readDirname = "" } = { ...defaultOptions, ...appOptions };
    // 解析路径, 输出路径配置的键值对对象
    const router = defineRouter(routes);
    // 中间件列表
    const middlewareList = [
        errorMiddleware,
        requestLocationMiddleware,
        requestQueryMiddleware,
        responseHeaderMiddleware,
        requestHandlerMiddleware // 执行请求对相应的方式执行接口或读取文件
    ];
    const server = createServer(serveOptions);
    server.on("request", combineMiddleware(middlewareList, {
        server,
        router,
        strict,
        readDirname // 用于读取文件的目录
    }));
    const app = {
        server,
        use(middleware) {
            middlewareList.push(middleware);
            return app;
        },
        listen(listenOptions, listener) {
            server.listen(listenOptions, () => {
                listener(server);
            });
        }
    };
    return app;
}
